package com.example.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author John
 */
@Aspect
@Component
public class AspectTest {
    private final static Logger logger = LoggerFactory.getLogger(AspectTest.class);

    long startTime = System.currentTimeMillis();


    @Pointcut("execution(public * com.example.controller..*(..))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void doBfore(JoinPoint joinPoint) {
        long endTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("url={}", request.getRequestURL());
        logger.info("method={}", request.getMethod());
        logger.info("ip={}", request.getRemoteAddr());
        logger.info("class_methodname={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint
                .getSignature().getName());
        logger.info("args={}", joinPoint.getArgs());
        logger.info("startTime={}", startTime);
        logger.info("endTime={}", endTime);
        logger.info("Before方法执行了...");
    }


    @After("pointcut()")
    public void deAfter(JoinPoint joinPoint) {
        long endTime = System.currentTimeMillis();
        logger.info("执行" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint
                .getSignature().getName() + "耗时为：" + (endTime - startTime) + "ms");
        logger.info("After方法执行了...");
    }

    @Around("pointcut()")
    public Object  doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("Around方法执行了...环绕开始");
        Object obj = joinPoint.proceed();
        logger.info("Around方法执行了...环绕结束");
        return obj;
    }

    @AfterReturning(value = "pointcut()",returning = "result")
    public void doAfterReturning(Object result){
        logger.info("AfterReturning方法执行了...返回结果是："+result);
    }

    @AfterThrowing(value = "pointcut()" , throwing = "e")
    public void doAfterThrowing(Exception e){
        logger.info("AfterThrowing方法执行了...异常为"+e);
    }


}
